#!/bin/zsh -Ndfgku
#
# Scripts/lint
# mas
#
# Copyright © 2025 mas-cli. All rights reserved.
#
# Reports style violations without making any modifications to the code.
#
# Please keep in sync with Scripts/format.
#

. "${0:A:h}/_setup_script"

print_notice '🚨 Linting' "${@}"

ensure_command_available actionlint git markdownlint-cli2 periphery shellcheck swiftformat swiftlint yamllint || exit

zmodload zsh/zutil
zparseopts -D -A received_flag A P

export -r MAS_INSTALL_METHOD=lint

integer exit_status=0

printf -- $'--> 🕊​ SwiftFormat\n'
script -q /dev/null swiftformat --lint --markdown-files format-strict . |
 (grep -vxE '(?:\^D\x08{2})?Running SwiftFormat\.{3}\r|\(lint mode - no files will be changed\.\)\r|Reading (?:config|swift-version) file at .*|\x1b\[32mSwiftFormat completed in \d+(?:\.\d+)?s\.\x1b\[0m\r|0/\d+ files require formatting\.\r|Source input did not pass lint check\.\r' || true)
((exit_status |= ${?}))

printf -- $'--> 🦅 SwiftLint\n'
swiftlint --strict --quiet --reporter relative-path
((exit_status |= ${?}))

# shellcheck disable=SC1046,SC1047,SC1072,SC1073
if ! [[ -v 'received_flag[-A]' ]]; then
	printf -- $'--> 🔬 SwiftLint Analyze\n'
	# shellcheck disable=SC1036
	swiftlint analyze --strict --quiet --reporter relative-path --compiler-log-path\
	 =(xcodebuild -scheme mas -destination "platform=macOS,arch=$(arch),variant=macos" 2>&1)
	((exit_status |= ${?}))
fi

if ! [[ -v 'received_flag[-P]' ]]; then
	printf -- $'--> 🌀 Periphery\n'
	script -q /dev/null periphery scan --exclude-tests |
	 (grep -vxE '(?:\x1b\[0;1;32m|\^D\x08{2})\* (?:\x1b\[0;0m\x1b\[0;1m)?No unused code detected\.(?:\x1b\[0;0m)?\r' || true)
	((exit_status |= ${?}))

	printf -- $'--> 🌀 Periphery Tests\n'
	script -q /dev/null periphery scan |
	 (grep -vxE '(?:\x1b\[0;1;32m|\^D\x08{2})\* (?:\x1b\[0;0m\x1b\[0;1m)?No unused code detected\.(?:\x1b\[0;0m)?\r' || true)
	((exit_status |= ${?}))
fi

printf -- $'--> 〽️ Markdown\n'
markdownlint-cli2 -- ***/*.md(.)
((exit_status |= ${?}))

printf -- $'--> 📝 YAML\n'
yamllint -s .
((exit_status |= ${?}))

printf -- $'--> 🌳 Git\n'
git diff --check
((exit_status |= ${?}))

printf -- $'--> 💤 Zsh\n'
for script in Scripts/***/*(.); do
	/bin/zsh -n "${script}"
	((exit_status |= ${?}))
done

printf -- $'--> 🐙 ActionLint\n'
actionlint -shellcheck shellcheck
((exit_status |= ${?}))

printf -- $'--> 🐚 ShellCheck\n'
shellcheck -s bash -o all -e SC1009,SC1088,SC2296,SC2298,SC2299,SC2300,SC2301,SC2312 -a -P SCRIPTDIR Scripts/***/*(.)
((exit_status |= ${?}))

printf -- $'--> 🚷 Non-Executables\n'
readonly -a non_executables=(Scripts/***/*(N.^f+111))
if (("${#non_executables[@]}")); then
	printf $'%s\n' "${non_executables[@]}"
	((exit_status |= 1))
fi

exit "${exit_status}"
